package com.run.runbbs.service.impl;

import com.run.runbbs.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;

@Service
public class LikeService {
    @Autowired
    private RedisTemplate redisTemplate;

    //点赞或取消点赞 entityType：1代表帖子，2代表评论 entityUserId:被点赞的用户，方便修改其获赞数量
    public void like(int userId,int entityType,int entityId,int entityUserId){
        redisTemplate.execute(new SessionCallback() {
            @Override
            public Object execute(RedisOperations redisOperations) throws DataAccessException {
                String entityLikeKey= RedisKeyUtil.getEntityLikeKey(entityType,entityId);
                //用户获得的赞的数量 的key
                String userLikeKey=RedisKeyUtil.getUserLikeKey(entityUserId);
                //isMember：根据key查看集合中是否存在指定数据，即查看用户是否点了赞
                boolean isMember=redisTemplate.opsForSet().isMember(entityLikeKey,userId);
                //开启事务
                redisOperations.multi();
                if(isMember){
                    redisOperations.opsForSet().remove(entityLikeKey,userId);
                    //减一
                    redisOperations.opsForValue().decrement(userLikeKey);
                }else{
                    redisOperations.opsForSet().add(entityLikeKey,userId);
                    //加一
                    redisOperations.opsForValue().increment(userLikeKey);
                }
                //执行事务
                return redisOperations.exec();
            }
        });
    }
    //查询某实体点赞的数量
    public long findEntityLikeCount(int entityType,int entityId){
        String entityLikeKey=RedisKeyUtil.getEntityLikeKey(entityType,entityId);
        return  redisTemplate.opsForSet().size(entityLikeKey);
    }

    //查询某人对实体的点赞状态（点赞1，未点赞0） 后面还可以弄踩
    public int findEntityLikeStatus(int userId,int entityType,int entityId){
        String entityLikeKey=RedisKeyUtil.getEntityLikeKey(entityType,entityId);
        return redisTemplate.opsForSet().isMember(entityLikeKey,userId)?1:0;
    }

    //查询某个用户获得的赞的数量
    public long findUserLikeCount(int userId){
        String userLikeKey=RedisKeyUtil.getUserLikeKey(userId);
        Integer count= (Integer) redisTemplate.opsForValue().get(userLikeKey);
        return count==null?0:count.intValue();
    }
    //查询某个用户获得的赞的详情

}
